/* eslint-disable @typescript-eslint/no-inferrable-types */
import {
  Controller,
  Body,
  Post,
  ConflictException,
  Delete,
  Param,
  Put,
  Get,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  Query,
  UseGuards,
} from '@nestjs/common';
import { CarwashesService } from './carwashes.service';
import { CarwashDto } from 'src/dto/carwash.dto';
import { MongoError } from 'mongodb';
import { FindDataDto } from 'src/dto/find-data.dto';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';

@UseGuards(JwtAuthGuard)
@Controller('carwashes')
export class CarwashesController {
  constructor(private readonly carwashesService: CarwashesService) {}

  /**
   * 创建一个洗车点
   * @param carwashDto 洗车点信息
   */
  @Post()
  async createCarwash(@Body() carwashDto: CarwashDto) {
    const createdCarwash = await this.carwashesService
      .create(carwashDto)
      .catch((mongoError: MongoError) => {
        console.log(mongoError);
        if (mongoError.code === 11000) {
          throw new ConflictException('请不要重复创建', '洗车点已经存在');
        }
        throw mongoError;
      });

    return createdCarwash;
  }

  /**
   * 删除一个洗车点
   * @param _id _id
   */
  @Delete(':_id')
  async deleteCarwash(@Param('_id') _id: string) {
    await this.carwashesService.deleteById(_id);
  }

  /**
   * 更新一个洗车点
   * @param _id _id
   * @param carwashDto 洗车点信息
   */
  @Put(':_id')
  async updateCarwash(
    @Param('_id') _id: string,
    @Body() carwashDto: CarwashDto,
  ) {
    await this.carwashesService.updateById(_id, carwashDto);
  }

  /**
   * 查询一些洗车点
   * @param pageIndex 页码
   * @param pageSize 页大小
   */
  @Get()
  async findCarwashes(
    @Query('pageIndex') pageIndex: number = 1,
    @Query('pageSize') pageSize: number = 10,
    @Query('keyword') keyword: string = '',
  ) {
    const data = await this.carwashesService.find({
      pageIndex,
      pageSize,
      keyword,
    });
    const total = await this.carwashesService.count({ keyword });

    return {
      total,
      pageIndex,
      pageSize,
      keyword,
      data,
    } as FindDataDto<CarwashDto>;
  }
}
